<?php

namespace backend\controllers;

use Yii;
use common\models\customelements\CustomElements;
use common\models\customelements\CustomElementsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\customset\CustomSet;

/**
 * CustomElementsController implements the CRUD actions for CustomElements model.
 */
class CustomElementsController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all CustomElements models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CustomElementsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single CustomElements model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new CustomElements model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CustomElements();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing CustomElements model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing CustomElements model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the CustomElements model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return CustomElements the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CustomElements::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 自定义表单
     */
    public function actionCustomerform()
    {
        if (Yii::$app->request->get()) {
            $id = Yii::$app->request->get()['id'];
        } else {
            $id = null;
        }

        $where = array('set_id' => $id);
        $set_info = CustomSet::find()->where($where)->asArray()->one();

        if (Yii::$app->request->post()) {

            $_POST["succ_info"] = (empty($_POST["succ_info"]) ? "提交成功" : Yii::$app->request->post("succ_info", "trim"));
            $_POST["err_info"] = (empty($_POST["succ_info"]) ? "提交失败" : Yii::$app->request->post("err_info", "trim"));

            $form_config = array();
            $form_config["limit_time"] = (int) $_POST["limit_time"];

            if ($_POST["limit_time"] == 1) {
                $form_config["startdate"] = strtotime($_POST["startdate"]);
                $form_config["enddate"] = strtotime($_POST["enddate"]);
            }
            else {
                $form_config["startdate"] = 0;
                $form_config["enddate"] = 0;
            }
            if(!$_POST['datebefore'])
            {
                $form_config["datebefore"] = 0;
            }
            else{
                $form_config["datebefore"] = (int) $_POST["datebefore"];
            }
            if(!$_POST['datelast'])
            {
                $form_config["datelast"] = 0;
            }
            else{
                $form_config["datelast"] = $_POST["datelast"];
            }
            $form_config["limit_nums_total"] = (int) ((isset($_POST["limit_nums_total"])) ? $_POST["limit_nums_total"] : null);
            $form_config["limit_once_total"] = (int) ((isset($_POST["limit_once_total"])) ? $_POST["limit_once_total"] : null);
            $form_config["limit_nums"] = (int) ((isset($_POST["limit_nums"])) ? $_POST["limit_nums"] : null);
            $form_config["limit_once"] = (int) ((isset($_POST["limit_once"])) ? $_POST["limit_once"] : null);

            if (isset($_POST["limit_nums_total"]) && $_POST["limit_nums_total"] == 1) {
                $form_config["putnums_total"] = (int) $_POST["putnums_total"];
            }
            else {
                $form_config["putnums_total"] = 0;
            }

            if (isset($_POST["limit_once_total"]) && $_POST["limit_once_total"] == 1) {
                $form_config["day_nums_total"] = (int) $_POST["day_nums_total"];
            }
            else {
                $form_config["day_nums_total"] = 0;
            }

            if (isset($_POST["limit_nums"]) && $_POST["limit_nums"] == 1) {
                $form_config["putnums"] = (int) $_POST["putnums"];
            }
            else {
                $form_config["putnums"] = 0;
            }

            if (isset($_POST["limit_once"]) && $_POST["limit_once"] == 1) {
                $form_config["day_nums"] = (int) $_POST["day_nums"];
            }
            else {
                $form_config["day_nums"] = 0;
            }

            // $notice_config = array();
            // $notice_config["open_notice"] = (int) (isset($_POST["open_notice"]) ? $_POST["open_notice"] : 0);

            // if (isset($_POST["open_notice"]) && $_POST["open_notice"] == 1) {
            //     $notice_config["email_notice"] = (int) (isset($_POST["email_notice"]) ? $_POST["email_notice"] : 0);
            //     $notice_config["open_notice_sms"] = (int) (isset($_POST["open_notice_sms"]) ? $_POST["open_notice_sms"] : 0);
            //     $notice_config["open_notice_weixin"] = (int) (isset($_POST["open_notice_weixin"]) ? $_POST["open_notice_weixin"] : 0);
            //     if ($_POST["open_notice_weixin"] == 1) {
            //         $notice_config["notice_weixin"] = trim($_POST["notice_weixin"]);
            //     }
            //     else
            //     {
            //         $notice_config["notice_weixin"] = "";
            //     }
            // }
            // else {
            //     $notice_config["open_notice"] = 0;
            //     $notice_config["email_notice"] = 0;
            //     $notice_config["open_notice_sms"] = 0;
            //     $notice_config["open_notice_weixin"] = 0;
            //     $notice_config["email_adds"] = "";
            //     $notice_config["email_name"] = "";
            //     $notice_config["public_email"] = "";
            //     $notice_config["public_password"] = "";
            //     $notice_config["notice_phone"] = "";
            //     $notice_config["notice_phone"] = "";
            //     $notice_config["notice_phone_once"] = 0;
            // }

            // $pay_config = array();
            // $pay_config["pay_notice_more"] = (int) (isset($_POST["pay_notice_more"]) ? $_POST["pay_notice_more"]: null);
            // $pay_config["pay_notice"] = (int) (isset($_POST["pay_notice"]) ? $_POST["pay_notice"]: null);
            // $limit = array("form_config" => serialize($form_config), "notice_config" => serialize($notice_config), "pay_config" => serialize($pay_config));
            $_POST["price"] = (string) (isset($_POST["price"]) ? $_POST["price"] * 100 : '');
            $component = json_decode($_POST["componentJsonStr"], true);

            foreach ($component["form"]["component"] as $key => $value ) {
                $insert[$key] = $value;
                $insert[$key]["numtype"] = (isset($value["numtype"]) ? $value["numtype"] : '');
                $insert[$key]["datetype"] = (isset($value["datetype"]) ? $value["datetype"] : "d");
                $insert[$key]["layout"] = (isset($value["layout"]) ? $value["layout"] : '');
                $insert[$key]["imgnum"] = (isset($value["imgnum"]) ? $value["imgnum"] : '');
                $insert[$key]["numbertype"] = (isset($value["numbertype"]) ? $value["numbertype"] : '');
                $insert[$key]["img"] = (isset($value["img"]) ? $value["img"] : '');
                $insert[$key]["imglink"] = (isset($value["imglink"]) ? $value["imglink"] : '');
                $insert[$key]["alignstyle"] = (isset($value["alignstyle"]) ? $value["alignstyle"] : '');
                $insert[$key]["titlealignstyle"] = (isset($value["titlealignstyle"]) ? $value["titlealignstyle"] : '');
                $insert[$key]["pictureshow"] = (isset($value["pictureshow"]) ? $value["pictureshow"] : '');
                $insert[$key]["subtitle"] = (isset($value["subtitle"]) ? $value["subtitle"] : '');
                $insert[$key]["snumber"] = (isset($value["snumber"]) ? $value["snumber"] : 9);
                $insert[$key]["stype"] = (isset($value["stype"]) ? $value["stype"] : 9);
                $insert[$key]["evalue"] = (isset($value["value"]) ? serialize($value["value"]) : "");
                $insert[$key]["token"] = trim(isset($value["token"]) ? $value["token"] : '');
                $insert[$key]["sort"] = $key;
            }

            $componentStyleJsonStr = json_decode($_POST["componentStyleJsonStr"], true);
            // $base_config = array();
            // $base_config["first_banner"] = $_POST["first_banner"];
            // $base_config["first_banner_url"] = trim($_POST["first_banner_url"]);
            // $base_config["second_banner"] = $_POST["second_banner"];
            // $base_config["second_banner_url"] = trim($_POST["second_banner_url"]);
            // $base_config["third_banner"] = $_POST["third_banner"];
            // $base_config["third_banner_url"] = trim($_POST["third_banner_url"]);
            // $base_config["first_icon"] = $_POST["first_icon"];
            // $base_config["second_icon"] = $_POST["second_icon"];
            // $base_config["third_icon"] = $_POST["third_icon"];
            // $base_config["fourth_icon"] = $_POST["fourth_icon"];
            // $base_config["title1"] = trim($_POST["title1"]);
            // $base_config["title2"] = trim($_POST["title2"]);
            // $base_config["footbtn_title"] = trim($_POST["footbtn_title"]);

            // foreach ($componentStyleJsonStr as $key => $value ) {
            //     $base_config["bodybgcolor"] = $componentStyleJsonStr["bodybgcolor"];
            //     $base_config["title1_config"] = (!empty($componentStyleJsonStr["title1"]) ? serialize($componentStyleJsonStr["title1"]) : "");
            //     $base_config["title2_config"] = (!empty($componentStyleJsonStr["title2"]) ? serialize($componentStyleJsonStr["title2"]) : "");
            //     $base_config["baseinfo_config"] = (!empty($componentStyleJsonStr["baseinfo"]) ? serialize($componentStyleJsonStr["baseinfo"]) : "");
            //     $base_config["hdtit_config"] = (!empty($componentStyleJsonStr["hdtit"]) ? serialize($componentStyleJsonStr["hdtit"]) : "");
            //     $base_config["hddesc_config"] = (!empty($componentStyleJsonStr["hddesc"]) ? serialize($componentStyleJsonStr["hddesc"]) : "");
            //     $base_config["optionvalue_config"] = (!empty($componentStyleJsonStr["optionvalue"]) ? serialize($componentStyleJsonStr["optionvalue"]) : "");
            //     $base_config["footbtn_config"] = (!empty($componentStyleJsonStr["footbtn"]) ? serialize($componentStyleJsonStr["footbtn"]) : "");
            //     $base_config["conbg"] = $componentStyleJsonStr["conbg"];
            // }
            if (Yii::$app->request->post()['set_id']) {
                unset($_POST["is_pay"]);
                unset($_POST["pay_name"]);
                unset($_POST["price"]);
                $setmodel = array();
                $setmodel['detail'] = isset($_POST['detail']) ? $_POST['detail'] : '';
                $setmodel['title'] = isset($_POST['title']) ? $_POST['title'] : '';
                $setmodel['keyword'] = isset($_POST['keyword']) ? $_POST['keyword'] : '';
                $setmodel['intro'] = isset($_POST['intro']) ? $_POST['intro'] : '';
                $setmodel['addtime'] = (string) time();
                $setmodel['top_pic'] = isset($_POST['top_pic']) ? $_POST['top_pic'] : '';
                $setmodel['succ_info'] = $_POST['succ_info'];
                $setmodel['err_info'] = $_POST['err_info'];
                // $setmodel->limit_id = $_POST['limit_id'];
                // $setmodel->token = $_POST['token'];

                $setmodel['tel'] = isset($_POST['tel']) ? $_POST['tel'] : '';
                $setmodel['address'] = isset($_POST['address']) ? $_POST['address'] : '';
                // $setmodel['longitude'] = $_POST['longitude'];
                // $setmodel['latitude'] = $_POST['latitude'];
                // $setmodel->is_pay = $_POST['is_pay'];
                $setmodel['pay_name'] = isset($_POST['pay_name']) ? $_POST['pay_name'] : '';
                $setmodel['price'] = isset($_POST['price']) ? $_POST['price'] : '';
                // $setmodel->follow = $_POST['follow'];
                // $setmodel->sms = $_POST['sms'];
                $setmodel['fixphone'] = isset($_POST['fixphone']) ? $_POST['fixphone'] : '';

                $seid = Yii::$app->request->post()['set_id'];
                Yii::$app->db->createCommand()->update('custom_set', $setmodel, ['set_id' => $seid])->execute();

                // $custom_elements_all = M("custom_elements")->where(array("set_id" => $set_info["set_id"], "token" => $this->token))->field("eid")->select();
                $custom_elements_all = CustomElements::find()->where(['set_id' => $seid])->select(['eid'])->asArray()->all();

                foreach ($custom_elements_all as $k => $v ) {
                    $eid[$v["eid"]] = $v["eid"];
                }

                foreach ($insert as $key => $value) {
                    unset($value['value']);
                    if (CustomElements::find()->where(['set_id' => $seid, 'eid' => $value["eid"]])->one()) {
                        unset($eid[$value["eid"]]);
                        Yii::$app->db->createCommand()->update('custom_elements', $value, ["eid" => $value["eid"]])->execute();
                    }
                    else {
                        Yii::$app->db->createCommand()->delete('custom_elements', ['set_id' => $seid, 'eid' => $value['eid']])->execute();
                        // M("custom_elements")->where(array("set_id" => $set_info["set_id"], "token" => $this->token, "eid" => $value["eid"]))->delete();
                        $value["set_id"] = $seid;
                        Yii::$app->db->createCommand()->insert('custom_elements', $value)->execute();
                        // M("custom_elements")->add($value);
                    }
                }

                $eids = implode(array_keys($eid), ",");

                if (!empty($eids)) {
                    Yii::$app->db->createCommand()->delete('custom_elements', ['set_id' => $seid, ['in', 'eid', $eids]])->execute();
 
                }


                return $this->redirect(["custom-elements/customerform?id=$seid"]);
            }
            else {

                if (empty($insert)) {
                        echo "<script>alert('请选择至少一个表单组件');history.go(-1);</script>";
                        return false;
                }
                // var_dump($limit);echo '<hr>';
                // var_dump($_POST);echo '<hr>';
                // var_dump(Yii::$app->request->post());echo '<hr>';
                //$id = $this->set_db->add($_POST);
                $setmodel = new CustomSet();
                $setmodel->title = isset($_POST['title']) ? $_POST['title'] : '';
                $setmodel->keyword = isset($_POST['keyword']) ? $_POST['keyword'] : '';
                $setmodel->intro = isset($_POST['intro']) ? $_POST['intro'] : '';
                $setmodel->addtime = (string) time();
                // $setmodel->top_pic = $_POST['top_pic'];
                $setmodel->succ_info = $_POST['succ_info'];
                $setmodel->err_info = $_POST['err_info'];
                $setmodel->detail = isset($_POST['detail']) ? $_POST['detail'] : '';
                // $setmodel->limit_id = $_POST['limit_id'];
                // $setmodel->token = $_POST['token'];

                $setmodel->tel = isset($_POST['tel']) ? $_POST['tel'] : '';
                $setmodel->address = isset($_POST['address']) ? $_POST['address'] : '';
                // $setmodel->longitude = $_POST['longitude'];
                // $setmodel->latitude = $_POST['latitude'];
                // $setmodel->is_pay = $_POST['is_pay'];
                // $setmodel->pay_name = $_POST['pay_name'];
                // $setmodel->price = $_POST['price'];
                // $setmodel->follow = $_POST['follow'];
                // $setmodel->sms = $_POST['sms'];
                $setmodel->fixphone = isset($_POST['fixphone']) ? $_POST['fixphone'] : '';
                // $setmodel->versions = $_POST['versions'];
                if (!$setmodel->save()) {
                    header("Content-type: text/html; charset=utf-8");
                    var_dump($setmodel->getErrors());die;
                }
                if ($setmodel->save()) {
                    $id =  $setmodel->set_id;
                }

                //$limit_id = $this->limit_db->add($limit);
                $_POST["addtime"] = time();
                //$_POST["limit_id"] = $limit_id;
                //var_dump($insert);
                //echo '<hr>';
                //echo '<hr>';


                    foreach ($insert as $key => $value ) {
                        $insert[$key]["set_id"] = $id;
                    }

                    foreach($insert as $t) {

                        $model = new CustomElements;

                        $model->name = $t['name'];
                        $model->eid = $t['eid'];
                        $model->title = $t['title'];
                        $model->required = (empty($t['required']) ? 0 :$t['required']);
                        $model->instruct = $t['instruct'];
                        $model->evalue = $t['evalue'];
                        $model->numtype = $t['numtype'];
                        $model->datetype = $t['datetype'];
                        $model->layout = $t['layout'];
                        $model->imgnum = $t['imgnum'];
                        $model->numbertype = $t['numbertype'];
                        $model->img = $t['img'];
                        $model->imglink = $t['imglink'];
                        $model->alignstyle = $t['alignstyle'];
                        $model->titlealignstyle = $t['titlealignstyle'];
                        $model->pictureshow = $t['pictureshow'];
                        $model->snumber = $t['snumber'];
                        $model->stype = $t['stype'];
                        $model->token = $t['token'];
                        $model->sort = $t['sort'];
                        $model->set_id = $t['set_id'];

                        // 保存组件

                        $model->save();

                    }

                    //var_dump($model);die;

                    //var_dump($insert);die;
                // if ($this->set_db->create()) {
                //     $_POST["detail"] = $this->_post("detail", "trim");
                //     $_POST["versions"] = 1;
                //     $id = $this->set_db->add($_POST);


                //     foreach ($insert as $key => $value ) {
                //         $insert[$key]["set_id"] = $id;
                //     }

                //     M("custom_elements")->addAll($insert);
                //     $base_config["set_id"] = $id;
                //     $base_config["token"] = $this->token;
                //     M("custom_base")->add($base_config);
                //     $this->handleKeyword($id, "Custom", $this->_post("keyword", "trim"), 1);
                //     $this->success("添加成功", U("Custom/index", array("token" => $this->token)));
                // }
                // else {
                //     $this->error($this->set_db->getError());
                // }
                    
                return $this->redirect(['custom-set/index']);
            }

        }
        else {
            
            // if (!empty($set_info)) {
            //     $limit_info = $this->limit_db->where(array("limit_id" => $set_info["limit_id"]))->find();
            // } else {
            //     $limit_info = null;
            // }

            if (!empty($set_info)) {
                // $custom_elements = M("custom_elements")->where(array("set_id" => $set_info["set_id"], "token" => $this->token))->order("sort asc,id asc")->select();
                $custom_elements = CustomElements::find()->where(['set_id' => $set_info["set_id"]])->orderBy("sort asc,id asc")->asArray()->all();
                foreach ($custom_elements as $key => $value ) {
                    if ($value["evalue"]) {
                        $custom_elements[$key]["value"] = unserialize($value["evalue"]);
                        unset($custom_elements[$key]["evalue"]);
                    }
                }
            }

            // $base_config = array();

            // if (!empty($set_info)) {
            //     $custom_base = M("custom_base")->where(array("set_id" => $set_info["set_id"], "token" => $this->token))->find();
            //     $base_config["bodybgcolor"] = $custom_base["bodybgcolor"];
            //     $base_config["title1"] = unserialize($custom_base["title1_config"]);
            //     $base_config["title2"] = unserialize($custom_base["title2_config"]);
            //     $base_config["baseinfo"] = unserialize($custom_base["baseinfo_config"]);
            //     $base_config["hdtit"] = unserialize($custom_base["hdtit_config"]);
            //     $base_config["hddesc"] = unserialize($custom_base["hddesc_config"]);
            //     $base_config["optionvalue"] = unserialize($custom_base["optionvalue_config"]);
            //     $base_config["conbg"] = $custom_base["conbg"];
            //     $base_config["footbtn"] = unserialize($custom_base["footbtn_config"]);
            // }

            // $form_config = unserialize($limit_info["form_config"]);
            // $notice_config = unserialize($limit_info["notice_config"]);
            // $pay_config = unserialize($limit_info["pay_config"]);

            // if (!empty($form_config)) {
            //     $set_info = array_merge($set_info, $form_config);
            // }

            // if (!empty($notice_config)) {
            //     $set_info = array_merge($set_info, $notice_config);
            // }

            $now = strtotime("+1 day");
            // $this->assign("now", $now);

            // hisWxUser = M("Wxuser")->where(array("token" => $this->token))->find();
            // $this->assign("smscount", M("Users")->where(array("id" => $thisWxUser["uid"]))->getField("smscount"));
            return $this->renderPartial('customerform', [
                'now' => $now,
                'set' => $set_info,
                'custom_elements' => !empty($custom_elements) ? json_encode($custom_elements) : "null",
                //'custom_base' => $custom_base,
                'base_config' => !empty($base_config) ? json_encode($base_config) : "null",

            ]);
        }
    }
}
